import 'dart:async';
import 'dart:io';
import 'package:audio_session/audio_session.dart';
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/im/person_info.dart';
import 'package:fate_blind_box/im/persondetail.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:fate_blind_box/im/video_model.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:image_picker/image_picker.dart';
import 'package:just_audio/just_audio.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import '../chat_view/chat_page_controller.dart';
import '../network/Api.dart';
import '../utils/loading.dart';
import '../utils/voice_animation_image.dart';
import 'msg_content.dart';


//聊天界面
class ChatPage extends StatefulWidget {
  final String easeuserId;

  const ChatPage(this.easeuserId, {Key? key}) : super(key: key);

  @override
  State<ChatPage> createState() => _ChatPageState();
}

enum RecordPlayState {
  record,
  recording,
  play,
  playing,
}

class _ChatPageState extends State<ChatPage> {
  VideoModel videoModel = VideoModel();
  final GlobalKey _formKey = GlobalKey<FormState>();
  final TextEditingController _messController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool canSend = false;
  late String centext;
  late String membersex = "";
  final List<String> _logText = [];
  Map<String, dynamic> map = {};
  final List<Map> _items = [];
  final ScrollController scrollController = ScrollController();
  FlutterSoundRecorder recorderModule = FlutterSoundRecorder();
  FlutterSoundPlayer playerModule = FlutterSoundPlayer();
  FlutterSound sound = FlutterSound();
  RecordPlayState _state = RecordPlayState.record;

  late StreamSubscription _recorderSubscription;
  late StreamSubscription _playerSubscription;

  late double _screenWidth, _screenHeight;
  List<dynamic> lists = [];
  List<EMMessage>? list = [];
  EMConversation? conversation;
  Map _userInfo = {};
  late Timer _timer;
  final player = AudioPlayer();
  final int _maxLength = 600;
  int num = 0;
  String voiceIco = "images/voice_volume_7.png";
  String _path = "";
  final List<String> _assetList = [
    "images/voice_volume_1.png",
    "images/voice_volume_2.png",
    "images/voice_volume_3.png",
    "images/voice_volume_4.png",
    "images/voice_volume_5.png",
    "images/voice_volume_6.png",
    "images/voice_volume_7.png",
  ];

  bool isStop = true;

  var isshouw = false;
  final List<dynamic?> _avatarList = [];

  bool emojiShowing = false;
  List<String> listr = [];
  ChatPageController chatPageController = Get.put(ChatPageController());

  @override
  void initState() {
    super.initState();
    if (CommonConfig.isHuaWeiPermission) {
      isOpenAudioPermission().then((value) {
        chatPageController.isShowAudioPermission = value;
        chatPageController.update([chatPageController.audioViewId]);
      });
    }
    init();
    if (kDebugMode) {
      print('rx--环信id--1111-----' + widget.easeuserId);
    }
    //  键盘自动收起
    _getUserinfo();
    initData();
    // setStatusBlackView(bgColor: ThemeColor.appColor);
    _addChatListener();
    if (lists.isNotEmpty) {
      setState(() {
        scrollController
            .jumpTo(scrollController.position.maxScrollExtent + 500);
      });
    }
  }

  Future<bool> isOpenAudioPermission() async {
    var status = await Permission.microphone.status;
    if (status.isGranted) {
      return false;
    }
    return true;
  }

  initData() async {
    try {
      // 会话 ID。
      String convId = widget.easeuserId;
// 如果会话不存在是否创建。设置为 `true`，则会返回会话对象。
      bool createIfNeed = true;
// 会话类型。详见 `EMConversationType` 枚举类型。
      EMConversationType conversationType = EMConversationType.Chat;
// 执行操作。
      conversation = await EMClient.getInstance.chatManager.getConversation(
        convId,
        type: conversationType,
        createIfNeed: true,
      );
      list = await conversation?.loadMessages();
      if (kDebugMode) {
        print('rx----获取回1-----' + list.toString());
      }
      // 成功加载会话。
      setState(() {
        // if (list!.isEmpty) {
        //   return;
        // }
        // list = list?.reversed.cast<EMMessage>().toList();
        lists.addAll(list!);
      });
    } on EMError catch (e) {}
  }

  showView() {
    showDialog(
        context: context,
        builder: (context) {
          return Center(
              child: SizedBox(
                  child: Stack(alignment: Alignment.topCenter, children: [
            Container(
                // decoration: BoxDecorationUtil().setFillBoxDecoration(Colors.white, 14.0),
                margin: const EdgeInsets.only(top: 35, right: 52, left: 52),
                child: Column(mainAxisSize: MainAxisSize.min, children: [
                  Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        VoiceAnimationImage(
                          _assetList,
                          100,
                          100,
                          isStop,
                        ),
                        // Image(
                        //    image: AssetImage(voiceIco),
                        //    width: 100,
                        //    height: 100),
                      ]),
                ]))
          ])));
        });

    setState(() {});
  }

  // 获取环信用户信息
  _getUserinfo() async {
    if (widget.easeuserId.isEmpty) return;
    final res = await Api.getInstance().getUserInfo(widget.easeuserId);
    final data = res['data'];
    if (data != null) {
      setState(() {
        _userInfo = data;
        if (_userInfo['realSex'] == 0) {
          membersex = '保密';
        }
        if (_userInfo['realSex'] == 1) {
          membersex = '男';
        }
        if (_userInfo['realSex'] == 2) {
          membersex = '女';
        }
      });
    } else {
      if (kDebugMode) {
        print('------获取用户异常---------------' + res['msg']);
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    //setStatusBlackView();
    if (mounted) {
      _focusNode.dispose();
      _messController.dispose();
      // _timer.cancel();
      recorderModule.closeRecorder();
      playerModule.closePlayer();
      // 移除消息状态监听
      EMClient.getInstance.chatManager
          .removeMessageEvent("YXA6hl6vye2MTQOb2k-1mAKAiA");
      // 移除收消息监听
      EMClient.getInstance.chatManager
          .removeEventHandler("YXA6hl6vye2MTQOb2k-1mAKAiA");
    }
  }

  void _addLogToConsole(String val) {
    _logText.add('输入----------------' ": " + val);
    setState(() {
      scrollController.jumpTo(scrollController.position.maxScrollExtent + 50);
    });
  }

  //修改状态栏
  void setStatusBlackView({Color? bgColor}) {
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
        statusBarColor: bgColor ?? Colors.transparent,
        statusBarIconBrightness: Brightness.dark);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }

  void validateInput(String test) {
    setState(() {
      canSend = test.isNotEmpty;
      centext = test;
    });
  }

  void sendMess() {
    if (!canSend) {
      return;
    }

    // 保证在组件build的第一帧时才去触发取消清空内容
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _messController.clear();
    });

    setState(() {
      canSend = false;
      if (widget.easeuserId.isEmpty && widget.easeuserId == null ||
          centext.isEmpty) {
        _addLogToConsole("id和内容为空");
        return;
      }

      var msg = EMMessage.createTxtSendMessage(
        targetId: widget.easeuserId,
        content: centext,
        chatType: ChatType.Chat,
      );
      
      
      if (kDebugMode) {
        print('rx--环信id-------' + widget.easeuserId);
        print('rx----内容-----ff' + centext);
      }
      EMClient.getInstance.isConnected().then((value) => {
            print('nnnn  $value ${msg.body}'),
            if (value)
              {
                EMClient.getInstance.chatManager.sendMessage(msg),
                initData(),
              }
            else
              {
                ThemeSnackBar.show(context, '已断线,请重新登陆~'),
                FocusScope.of(context).unfocus()
                // Provider.remove('token'),
                // Provider.toLogin(),
              }
          });
    });
  }

  Future<void> openTheRecorder() async {
    if (!kIsWeb) {
      try {
        var status = await Permission.microphone.request();
        if (status != PermissionStatus.granted) {
          throw RecordingPermissionException(
              'Microphone permission not granted');
        }
      } catch (e) {
        print(e);
      }
    }
  }

  void init() async {
    print('开启录音权限');
    await openTheRecorder();
    //开启录音
    await recorderModule.openRecorder();
    //设置订阅计时器
    await recorderModule
        .setSubscriptionDuration(const Duration(milliseconds: 10));

    //设置音频
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
              AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
    await playerModule.closePlayer();
    await playerModule.openPlayer();
    await playerModule
        .setSubscriptionDuration(const Duration(milliseconds: 10));
  }

  //动态获取权限
  Future<bool> getPermissionStatus() async {
    Permission permission = Permission.microphone;
    //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
    PermissionStatus status = await permission.status;
    print('nnnn $status');
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      openAppSettings();
    } else if (status.isRestricted) {
      requestPermission(permission);
    } else {}
    return false;
  }

  /// 开始录音
  _startRecorder() async {
    try {
      var status = await getPermissionStatus();

      Directory tempDir = await getTemporaryDirectory();
      var time = DateTime.now().millisecondsSinceEpoch;
      String path = '${tempDir.path}$time${ext[Codec.amrWB.index]}';

      if (kDebugMode) {
        print('===>  准备开始录音');
      }
      await recorderModule.startRecorder(
        toFile: path,
        codec: Codec.amrWB,
        bitRate: 1411200,
        sampleRate: 44100,
      );
      if (kDebugMode) {
        print('===>  开始录音');
      }

      /// 监听录音
      recorderModule.onProgress!.listen((e) {
        DateTime date = DateTime.fromMillisecondsSinceEpoch(
            e.duration.inMilliseconds,
            isUtc: true);

        if (date.second >= _maxLength) {
          if (kDebugMode) {
            print('===>  到达时常停止录音');
          }
          _stopRecorder();
        }
        setState(() {
          if (kDebugMode) {
            print("时间：${date.second}");
          }
          if (kDebugMode) {
            print("当前振幅：${e.decibels}");
          }
          num = date.second;
          setState(() {
            if (e.decibels! > 0 && e.decibels! < 10) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              voiceIco = "images/voice_volume_1.png";
            } else if (e.decibels! > 20 && e.decibels! < 30) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              voiceIco = "images/voice_volume_2.png";
            } else if (e.decibels! > 30 && e.decibels! < 40) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              voiceIco = "images/voice_volume_3.png";
            } else if (e.decibels! > 40 && e.decibels! < 50) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              voiceIco = "images/voice_volume_4.png";
            } else if (e.decibels! > 50 && e.decibels! < 60) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              voiceIco = "images/voice_volume_5.png";
            } else if (e.decibels! > 70 && e.decibels! < 100) {
              if (kDebugMode) {
                print('----${e.decibels}------------');
              }
              voiceIco = "images/voice_volume_6.png";
            } else {
              voiceIco = "images/voice_volume_7.png";
            }
          });
        });
      });
      setState(() {
        _state = RecordPlayState.recording;
        _path = path;

        if (kDebugMode) {
          print("path == $path");
        }
      });
    } catch (err) {
      setState(() {
        if (kDebugMode) {
          print(err.toString());
        }
        _stopRecorder();
        _state = RecordPlayState.record;
      });
    }
  }

  /// 结束录音
  Future<String?> _stopRecorder() async {
    var s = await recorderModule.stopRecorder();
    if (kDebugMode) {
      print('stopRecorder===> fliePath:$_path');
      // EMMessage.createVoiceSendMessage(targetId: targetId, filePath: _path);
    }
    // widget.stopRecord!(_path, num);

    setState(() {
      _state = RecordPlayState.play;
    });
    return s;
  }

  ///开始播放，这里做了一个播放状态的回调
  void startPlayer(path, {Function(dynamic)? callBack}) async {
    try {
      if (path.contains('http')) {
        await playerModule.startPlayer(
            fromURI: path,
            codec: Codec.mp3,
            sampleRate: 44000,
            whenFinished: () {
              stopPlayer();
              callBack!(0);
            });
      } else {
        //判断文件是否存在
        if (await _fileExists(path)) {
          if (playerModule.isPlaying) {
            playerModule.stopPlayer();
          }
          await playerModule.startPlayer(
              fromURI: path,
              codec: Codec.amrWB,
              sampleRate: 44000,
              whenFinished: () {
                stopPlayer();
                callBack!(0);
              });
        } else {}
      }
      //监听播放进度
      playerModule.onProgress!.listen((e) {});
      callBack!(1);
    } catch (err) {
      callBack!(0);
    }
  }

  /// 结束播放
  void stopPlayer() async {
    try {
      await playerModule.stopPlayer();
    } catch (err) {}
  }

  ///获取播放状态
  Future getPlayState() async {
    return await playerModule.getPlayerState();
  }

  /// 释放播放器
  void releaseFlauto() async {
    try {
      await playerModule.closePlayer();
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  /// 判断文件是否存在
  Future _fileExists(String path) async {
    return await File(path).exists();
  }

  ///申请权限
  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    if (status.isPermanentlyDenied) {
      openAppSettings();
    }
  }

  void _addChatListener() {
    // 添加消息状态变更监听
    EMClient.getInstance.chatManager.addMessageEvent(
        // ChatMessageEvent 对应的 key。
        "YXA6hl6vye2MTQOb2k-1mAKAiA",
        ChatMessageEvent(
          onSuccess: (msgId, msg) {
            //更新消息
            conversation?.updateMessage(msg);
            initData();
            print('发送消息成功---------');
            // _addLogToConsole("发送消息成功");
          },
          onProgress: (msgId, progress) {
            // _addLogToConsole("send message succeed");
          },
          onError: (msgId, msg, error) {
            if (kDebugMode) {
              print('rx----获取失败-----' + error.toString());
            }
          },
        ));

    // 添加收消息监听
    EMClient.getInstance.chatManager.addEventHandler(
      // EMChatEventHandler 对应的 key。
      "YXA6hl6vye2MTQOb2k-1mAKAiA",
      EMChatEventHandler(
        onMessagesReceived: (messages) async {
          player.setAsset('images/music_reveice.mp3');
          final session = await AudioSession.instance;
          session.configure(const AudioSessionConfiguration.music());
          player.play();

          for (var msg in messages) {
            switch (msg.body.type) {
              case MessageType.TXT:
                {
                  EMTextMessageBody body = msg.body as EMTextMessageBody;

                  conversation?.updateMessage(msg);
                  initData();

                  // print('rx--环信id-------' + body.toString());
                  // print('rx----收到内容-----' + body.content);
                  _addLogToConsole(
                    "收到文字消息:}",
                  );
                }
                break;
              case MessageType.IMAGE:
                {
                  _addLogToConsole(
                    "收到图片信息, from: ${msg.from}",
                  );
                }
                break;
              case MessageType.VIDEO:
                {
                  _addLogToConsole(
                    "收到视频信息, from: ${msg.from}",
                  );
                }
                break;
              case MessageType.LOCATION:
                {
                  _addLogToConsole(
                    "收到位置信息, from: ${msg.from}",
                  );
                }
                break;
              case MessageType.VOICE:
                {
                  // EMTextMessageBody body = msg.body as EMTextMessageBody;
                  conversation?.updateMessage(msg);
                  initData();
                  _addLogToConsole(
                    "收到语音消息:}",
                  );
                }
                break;
              case MessageType.FILE:
                {
                  _addLogToConsole(
                    "收到图片信息, from: ${msg.from}",
                  );
                }
                break;
              case MessageType.CUSTOM:
                {
                  _addLogToConsole(
                    "接受自定义信息, from: ${msg.from}",
                  );
                }
                break;
              case MessageType.CMD:
                {
                  // 当前回调中不会有 CMD 类型消息，CMD 类型消息通过 `EMChatEventHandler#onCmdMessagesReceived` 回调接收
                }
                break;
            }
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    int age = _userInfo['age'] ?? 0;
    String sexStr = _userInfo['realSex'] == 2 ? '女' : '男';
    return Scaffold(
      appBar: AppWidget.titleBar(_userInfo['nickName'] ?? "",
          backgroundColor: ThemeColor.grayF2F4F5Color,
          actions: [
            UnconstrainedBox(
              child: GestureDetector(
                  onTap: () {
                    if (_userInfo.isEmpty) return;
                    Get.to(PersonDatail(userInfo: _userInfo),
                        routeName: PageRouteNames.personDetailPage);
                  },
                  child: Container(
                    padding: const EdgeInsets.only(right: 15),
                    child: const Icon(
                      Icons.more_horiz,
                      size: 22,
                      color: Colors.black,
                    ),
                  )),
            ),
          ]),
      backgroundColor: ThemeColor.grayF2F4F5Color,
      body: Column(
        children: <Widget>[
          Container(
            height: 62,
            margin: const EdgeInsets.fromLTRB(19, 0, 20, 20),
            padding: const EdgeInsets.symmetric(horizontal: 12),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(5)),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () {
                    if (_userInfo['id'].toString().isEmpty) return;
                    // setStatusBlackView();
                    Get.to(PersonInfo(sig: _userInfo['id'].toString()),
                        routeName: PageRouteNames.personInfoPage);
                  },
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(3),
                    child: Image.network(
                      Provider.fixAvatar(_userInfo['profilePhoto']),
                      width: 30,
                      height: 30,
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                getCornerView(leftTitle: '年龄', rightTitle: age.toString()),
                const SizedBox(
                  width: 7,
                ),
                getCornerView(leftTitle: '性别', rightTitle: sexStr),
              ],
            ),
          ),
          Expanded(child: ListView.builder(
            controller: scrollController,
            padding: const EdgeInsets.only(left: 10, right: 10),
            itemBuilder: (_, index) {
              if (list?.isNotEmpty == true) {
                return MessageContent(
                    list!, index, Provider.userEaseName, _avatarList);
              } else {
                return Container();
              }
            },
            itemCount: list?.length,
          )),
          Container(
            height: !emojiShowing?56.w+ScreenUtil().bottomBarHeight:56.w,
            alignment: Alignment.topCenter,
            padding: EdgeInsets.only(top: 13.w,left: 10.w,right: 10.w),
            decoration: BoxDecoration(
              //背景
              color: Colors.white,
              //设置四周边框
              border: Border.all(width: 1, color: Colors.white),
            ),
            child: Row(
              children: [
                Visibility(
                  visible: true,
                  child: InkWell(
                    onTap: () {
                      emojiShowing = false;
                      //做弹起动画
                      if (isshouw) {
                        isshouw = false;
                        FocusScope.of(context).requestFocus(_focusNode); // 获取焦点
                      } else {
                        isshouw = true;
                        _focusNode.unfocus();
                      }
                    },
                    child: Container(
                      width: 24.w,
                      height: 24.w,
                      margin: const EdgeInsets.only(right: 5),
                      child: Image.asset(
                        'images/ic_volume.png',
                        width: 24,
                        height: 24,
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Offstage(
                    offstage: isshouw,
                    child: SizedBox(
                      child: Form(
                          key: _formKey,
                          child: SingleChildScrollView(
                            child: TextFormField(
                                autofocus: false,
                                maxLines: 1,
                                controller: _messController,
                                focusNode: _focusNode,
                                onChanged: validateInput,
                                onTap: () {
                                  setState(() {
                                    emojiShowing = false;
                                  });
                                },
                                keyboardType: TextInputType.text,
                                style: TextStyle(
                                  color: '#000000'.stringToColor,
                                  fontSize: 14.sp,
                                  fontWeight:FontWeight.w400,
                                ),
                                decoration: InputDecoration(
                                  isCollapsed: true,
                                  fillColor: const Color(0xffF1F3FB),
                                  filled: true,
                                  hintText: '输入消息内容…',
                                  hintStyle: TextStyle(
                                    color: '#8282A7'.stringToColor,
                                    fontSize: 12.sp,
                                    fontWeight:FontWeight.w400,
                                  ),

                                  contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 15, vertical: 10),
                                  enabledBorder: const OutlineInputBorder(
                                    /*边角*/
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(30), //边角为30
                                    ),
                                    borderSide: BorderSide(
                                      color: Colors.white54, //边线颜色为黄色
                                      width: 1, //边线宽度为2
                                    ),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(30),
                                      borderSide: const BorderSide(
                                        color: Colors.white54, //边框颜色为绿色
                                        width: 1, //宽度为5
                                      )),
                                )),
                          ),),
                    ),
                  ),
                ),
                SizedBox(width: 8.w),
                Offstage(
                  offstage: !isshouw,
                  child: Listener(
                    onPointerDown: (event) {
                      videoModel.sentimer();
                      //做弹起动画
                      print('长按或点击开始');
                      showView();
                      _startRecorder();
                    },
                    onPointerUp: (event) async {
                      var s = await _stopRecorder();
                      print('长按结束        $s');

                      print('nnn ${videoModel.isStop}');
                      if (videoModel.isStop) {
                        print('ppppppppp');
                        if (videoModel.indexPopTime
                                .difference(videoModel.lastPopTime) <
                            const Duration(milliseconds: 500)) {
                          if (kDebugMode) {
                            print('长按结束');
                          }

                          if (s.toString().isEmpty) return;
                          EMMessage message = EMMessage.createVoiceSendMessage(
                            targetId: widget.easeuserId,
                            filePath: s.toString(),
                            duration: num,
                            chatType: ChatType.Chat,
                          );

                          // 发送消息
                          EMClient.getInstance.chatManager.sendMessage(message);
                          player.setAsset('images/music_send.mp3');
                          final session = await AudioSession.instance;
                          session.configure(
                              const AudioSessionConfiguration.music());
                          player.play();
                          initData();
                        } else {
                          print('点击结束');
                        }
                      }
                      Navigator.pop(context);
                      if (videoModel.timer.isActive) {
                        videoModel.timer.cancel();
                      }
                    },
                    child: Container(
                      height: 40,
                      margin: const EdgeInsets.only(right: 3, left: 5),
                      padding: const EdgeInsets.symmetric(
                          vertical: 10, horizontal: 60),
                      decoration: const BoxDecoration(
                        color: Color(0xffF1F3FB),
                        borderRadius: BorderRadius.all(Radius.circular(30)),
                      ),
                      child: Text(
                        "按住 说话",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: ThemeColor.textColor,
                            fontSize: 14,
                            fontWeight: FontWeight.normal),
                      ),
                    ),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 5),
                  child: InkWell(
                    onTap: () {
                      print('表情符号');
                      setState(() {
                        emojiShowing = !emojiShowing;
                        _focusNode.unfocus();
                        if (isshouw) {
                          isshouw = false; // 获取焦点
                        }
                      });
                    },
                    child: Image.asset(
                      'images/ic_emojis.png',
                      width: 24,
                      height: 24,
                    ),
                  ),
                ),
                !canSend
                    ? Visibility(
                        visible: CommonConfig.isShowPay(),
                        child: Container(
                          margin: const EdgeInsets.only(left: 5),
                          child: InkWell(
                            onTap: () {
                              print('发送图片');
                              setState(() {
                                emojiShowing = false;
                              });
                              _checkAvatar();
                            },
                            child: Image.asset(
                              'images/ic_adds.png',
                              width: 24,
                              height: 24,
                            ),
                          ),
                        ),
                      )
                    : Container(),
                Offstage(
                  offstage: !canSend,
                  child: InkWell(
                    onTap: () {
                      listr.clear();
                      list?.clear();
                      sendMess();
                    },
                    child: Container(
                      margin: const EdgeInsets.only(left: 5),
                      padding: const EdgeInsets.only(
                          left: 10, right: 10, top: 8, bottom: 8),
                      decoration: const BoxDecoration(
                        color: Colors.green,
                        borderRadius: BorderRadius.all(Radius.circular(3)),
                      ),
                      child: Text(
                        "确定",
                        style: TextStyle(
                            color: ThemeColor.shadowColor,
                            fontSize: 14,
                            fontWeight: FontWeight.normal),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Offstage(
            offstage: !emojiShowing,
            child: SizedBox(
                height: 250,
                child: EmojiPicker(
                  textEditingController: _messController,
                  onBackspacePressed: _onBackspacePressed,
                  onEmojiSelected: (value, e) {
                    print('vv    $e');
                    setState(() {
                      canSend = true;
                      listr.add(e.emoji);
                      centext = listr.join('');
                    });
                  },
                  config: Config(
                    columns: 7,
                    emojiSizeMax: 32 *
                        (foundation.defaultTargetPlatform == TargetPlatform.iOS
                            ? 1.30
                            : 1.0),
                    verticalSpacing: 0,
                    horizontalSpacing: 0,
                    gridPadding: EdgeInsets.zero,
                    // initCategory: Category.RECENT,
                    bgColor: const Color(0xFFF2F2F2),
                    indicatorColor: ThemeColor.appColor,
                    iconColor: Colors.grey,
                    iconColorSelected: ThemeColor.appColor,
                    backspaceColor: ThemeColor.appColor,
                    skinToneDialogBgColor: Colors.white,
                    skinToneIndicatorColor: Colors.grey,
                    enableSkinTones: true,
                    recentTabBehavior: RecentTabBehavior.RECENT,
                    recentsLimit: 28,
                    replaceEmojiOnLimitExceed: false,
                    noRecents: const Text(
                      'No Recents',
                      style: TextStyle(fontSize: 20, color: Colors.black26),
                      textAlign: TextAlign.center,
                    ),
                    loadingIndicator: const SizedBox.shrink(),
                    tabIndicatorAnimDuration: kTabScrollDuration,
                    categoryIcons: const CategoryIcons(),
                    buttonMode: ButtonMode.MATERIAL,
                    checkPlatformCompatibility: true,
                  ),
                )),
          ),
        ],
      ),
    );
  }

  Widget getCornerView({String leftTitle = '', String rightTitle = ''}) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 8),
      decoration: BoxDecoration(
          color: ThemeColor.grayF2F4F5Color,
          borderRadius: BorderRadius.circular(12)),
      child: Text(
        leftTitle + '：' + rightTitle,
        style: TextStyle(color: ThemeColor.textColor3, fontSize: 10),
      ),
    );
  }

  _onBackspacePressed() {
    print('hhhh $listr');
    setState(() {
      canSend = _messController.text.characters.toString().isNotEmpty;
      centext = _messController.text.characters.toString();
    });
  }

  _checkAvatar() {
    if (!kIsWeb) {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: ImageSource.gallery);

        if (pickerFile != null) {
          //裁剪后图片的路径
          String filepath = pickerFile.path;
          if (filepath.toString().isEmpty) return;
          EMMessage message = EMMessage.createImageSendMessage(
            targetId: widget.easeuserId,
            filePath: filepath.toString(),
            chatType: ChatType.Chat,
          );
          EMClient.getInstance.chatManager.sendMessage(message);
        }
      });
    }
  }
}
